import React, { PureComponent } from 'react';
import { connect } from 'dva';
import { Form } from '@ant-design/compatible';
import '@ant-design/compatible/assets/index.css';
import moment from 'moment';
import 'moment/locale/zh-cn';
import { getMonthFirstDay } from '../../../utils/utils';
import { PrimaryGhostC, SecondHeaderC, DATA_ENTRY, AdvancedSearch, ContentPackage } from '../../../comps';
import myStyle from './index.less';
import CalendarC from './CalendarC';
import DateCardC from './dateCardC';
import MsgC from './MsgC';
import CashRemainC from './cashRemainC';
import RegisterC from './registerC';
import ProductC from './productC';
import AcitonC from './actionC';
import TradeC from './tradeC';
moment.locale('zh-cn');
const dateFormat = 'YYYY-MM-DD';

@connect(({ portfolioOptimizationM, loading }) => ({
  portfolioOptimizationM,
  loading,
}))
@Form.create()
export default class CalendarNew extends PureComponent {
  state = {
    portfolioCode: undefined, //组合的code
    portfolioCodeList: undefined, //点击查询时在赋值
    currentDate: moment().format('YYYY-MM-DD'), //选中的当前日期
    currentTime: new Date().getTime(),
  };

  componentDidMount() {
    // 适配用户视图跳转至,定位指定的产品、日期
    if (!!sessionStorage.getItem('jumpInfo')) {
      const obj = JSON.parse(sessionStorage.getItem('jumpInfo'));
      if (obj.type == '14' || obj.type == '15') {
        this.childSearch.props.form.setFieldsValue({
          portfolioId: [obj.portfolioId],
          date: moment(),
        });
        this.setState({
          portfolioCode: obj.portfolioCode,
          portfolioCodeList: obj.portfolioCode,
          currentDate: moment().format('YYYY-MM-DD'),
        });
        sessionStorage.removeItem('jumpInfo');
      }
    }
  }

  UNSAFE_componentWillReceiveProps() {
    // 适配用户视图跳转至,定位指定的产品、日期
    if (!!sessionStorage.getItem('jumpInfo')) {
      const obj = JSON.parse(sessionStorage.getItem('jumpInfo'));
      if (obj.type == '14' || obj.type == '15') {
        this.childSearch.props.form.setFieldsValue({
          portfolioId: [obj.portfolioId],
          date: moment(),
        });
        this.setState({
          portfolioCode: obj.portfolioCode,
          portfolioCodeList: [obj.portfolioCode],
          currentDate: moment().format('YYYY-MM-DD'),
        });
        sessionStorage.removeItem('jumpInfo');
      }
    }
  }
  componentWillUnmount() {
    //离开时清空model里的缓存数据
  }

  //选择了哪一天 调用方法
  handleSelectedDate = (e) => {
    this.setState({
      currentDate: e.format(dateFormat),
    });
    //如果新选中月份 与原来的年月不一致 则更新时间戳 重新请求数据
    if (moment(this.state.currentDate).format('YYYY-MM') != moment(e).format('YYYY-MM')) {
      this.setState({
        currentTime: new Date().getTime(),
      });
    }
    //变更date表单值 年月不同 则变更
    if (e.format('YYYY-MM') != this.childSearch.props.form.getFieldsValue().date.format('YYYY-MM')) {
      this.childSearch.props.form.setFieldsValue({
        date: e,
      });
    }
  };

  //点击今天
  handleToday = () => {
    this.childSearch.handleReset(); //重置搜索条件
    this.setState({
      portfolioCode: undefined,
      portfolioCodeList: undefined,
      currentDate: moment().format('YYYY-MM-DD'),
    });
    //如果选中月份 不是今天所在的月份 则更新时间戳 重新请求数据
    if (moment().format('YYYY-MM') != moment(this.state.currentDate).format('YYYY-MM')) {
      this.setState({
        currentTime: new Date().getTime(),
      });
    }
  };

  //消息变更 更新汇总表信息
  updateMsg = (list) => {
    let arr = list.map((item) => item.message);
    this.calendar.upDateMsgList(this.state.currentDate, arr);
  };

  render() {
    const { portfolioCodeList, currentTime, currentDate } = this.state;
    const searchProps = {
      selfButt: <PrimaryGhostC title='今天' style={{ marginLeft: '16px', borderRadius: '2px' }} onClick={this.handleToday} />,
      allowClear: false,
      dataSource: [
        {
          dataIndex: 'portfolioId',
          title: '组合选择',
          type: DATA_ENTRY.PRODUCTGROUPTREE,
          multiple: true,
          treeCheckable: true,
          onChange: (e) => {
            if (e) {
              //后台需要code 故进行转换
              const arr = [];
              e.info.map((item) => {
                arr.push(item.portfolioCode);
              });
              this.setState({
                portfolioCode: [...arr],
              });
            } else {
              this.setState({
                portfolioCode: undefined,
              });
            }
          },
        },
        {
          dataIndex: 'date',
          title: '日期选择',
          type: DATA_ENTRY.SINGLEDATE,
          initialValue: moment(),
          dataType: 'month',
          allowClear: false,
        },
      ],
      onQuery: (e) => {
        const date = getMonthFirstDay(e.date);
        this.setState({
          currentDate: date.format('YYYY-MM-DD'),
          portfolioCodeList: this.state.portfolioCode ? [...this.state.portfolioCode] : this.state.portfolioCode,
          currentTime: new Date().getTime(),
        });
      },
      onRef: (ref) => {
        this.childSearch = ref;
      },
    };
    return (
      <ContentPackage
        title='组合日历'
        contentHtml={
          <div className={myStyle.calendarNew}>
            <div className={myStyle.cardBody}>
              <AdvancedSearch {...searchProps} />
            </div>
            <div className='firstRow'>
              <div>
                {/* 日历部分 */}
                <CalendarC
                  onSelect={this.handleSelectedDate}
                  portfolioCodeList={portfolioCodeList}
                  date={currentDate}
                  onRef={(ref) => {
                    this.calendar = ref;
                  }}
                  currentTime={currentTime}
                />
              </div>
              <div>
                {/* 右侧日期卡片展示 */}
                <DateCardC date={currentDate} />
                {/* 右侧消息列表 */}
                <MsgC portfolioCodeList={portfolioCodeList} date={currentDate} currentTime={currentTime} onChange={this.updateMsg} />
                <div style={{ marginTop: '20px' }}>
                  <SecondHeaderC title={'现金余额'} />
                </div>
                <CashRemainC portfolioCodeList={portfolioCodeList} date={currentDate} currentTime={currentTime} />
                <div style={{ marginTop: '20px' }}>
                  <SecondHeaderC title={'登记事件'} />
                </div>
                <RegisterC portfolioCodeList={portfolioCodeList} date={currentDate} currentTime={currentTime} />
              </div>
            </div>
            {/* 产品事件 */}
            <ProductC portfolioCodeList={portfolioCodeList} date={currentDate} currentTime={currentTime} />
            {/* 行为事件 */}
            <AcitonC portfolioCodeList={portfolioCodeList} date={currentDate} currentTime={currentTime} />
            {/* 交易事件 */}
            <TradeC portfolioCodeList={portfolioCodeList} date={currentDate} currentTime={currentTime} />
          </div>
        }
      />
    );
  }
}
